﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp3_Grid
{
    /// <summary>
    /// TestElementTreeWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestElementTreeWindow : Window
    {
        DependencyObject selectElement = null;

        public TestElementTreeWindow()
        {
            InitializeComponent();

            this.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(HandlePreviewMouseLeftButtonDown);
        }

        private void HandlePreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                selectElement = e.OriginalSource as DependencyObject;
                this.DisplaySelectElement.Text = " 你选择的控件：" + selectElement.GetType().Name;
                DependencyObject dobj = GetTemplateParent(selectElement);
                if (dobj != null)
                {
                    this.DisplaySelectElementTemplateParent.Text = " 你选择的控件模板：" + dobj.GetType().Name;
                }
                else
                {
                    this.DisplaySelectElementTemplateParent.Text = "";
                }
                e.Handled = true;
            }
        }

        private DependencyObject GetTemplateParent(DependencyObject depObj)
        {
            FrameworkElement fe = depObj as FrameworkElement;
            FrameworkContentElement fce = depObj as FrameworkContentElement;

            DependencyObject result;
            if (fe != null)
            {
                result = fe.TemplatedParent;
            }
            else if (fce != null)
            {
                result = fce.TemplatedParent;
            }
            else
            {
                result = null;
            }
            return result;
        }

        private void OnDisplayLogicalTree(object sender, RoutedEventArgs e)
        {
            if (selectElement != null)
            {
                DisplayTreeWindow createWin = new DisplayTreeWindow();
                createWin.CreateLogicalTree(selectElement);
                createWin.Show();
            }
        }

        private void OnDisplayVisualTree(object sender, RoutedEventArgs e)
        {
            if (selectElement != null)
            {
                DisplayTreeWindow createWin = new DisplayTreeWindow();
                createWin.CreateVisualTree(selectElement);
                createWin.Show();
            }
        }
    }
}
